package com.cwt_taxi_xa.protocol;

import android.util.Log;

import com.cwt_taxi_xa.constants.MyStatus;
import com.cwt_taxi_xa.model.AreaFence;
import com.cwt_taxi_xa.protocol.socket.SocketManager;
import com.cwt_taxi_xa.timer.TimerConnecter;
import com.cwt_taxi_xa.timer.TimerHeartBeat;
import com.cwt_taxi_xa.util.AppLog;
import com.cwt_taxi_xa.util.ExceptionUtil;
import com.cwt_taxi_xa.util.StringUtil;
import com.cwt_taxi_xa.util.Tools;

import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;

import java.util.List;
import java.util.Timer;


/**
 * @author zr
 *
 */
public class DispatchCenterUsers {
	private static final String TAG = "DispatchCenterUsers";
	public static ClientBootstrap bootstrap = null;
	public static ChannelFuture channelFuture = null;
	public static boolean isConnTimer = false;
	public static int connectionMode = 1; //1 自动 2 手动
	public static Channel channel = null;

	public static int times = 0;

	//链接timer相关
	public static Timer connTimer = null;
	public static TimerConnecter timerConnecter = null;

	//心跳timer相关
	public static Timer heartTimer = null;
	public static TimerHeartBeat heartTask = null;


	public static SocketManager socketManager = new SocketManager();


	/**
	 * 检测连接参数
	 * @return
	 */
	public static boolean checkConnParam(){
		try {
			String ip = null;
			String port = null;
			int hytdswitch = DeviceBiz.getSwitcher();
			//判断主服务器是否打开，如果主服务器关闭怎获取备用服务器
			if(hytdswitch == 1){
				ip = DeviceBiz.getIp();
				port = DeviceBiz.getPort();
			}else{
				//判断副服务器是否打开，如果副服务器打开，用付服务器
//				int hytdswitchBak = DeviceBiz.getSwitcherBak();
//				if(hytdswitchBak == 1){
//					ip = DeviceBiz.getIpBak();
//					port = DeviceBiz.getPortBak();
//				}
			}

			if(!StringUtil.isNull(ip) && !StringUtil.isNull(port)){
				AppLog.i("【通讯平台】Client: 检测连接参数:true");
				return true;
			}else{
				AppLog.e("【通讯平台】Client: 检测连接参数:false,IP或端口为空");
				return false;
			}

		} catch (Exception e) {
			AppLog.e(ExceptionUtil.getInfo(e));
			e.printStackTrace();
		}
		AppLog.e("【通讯平台】Client: 检测连接参数:false,IP或端口为空");
		return false;
	}

	/**
	 * 启动连接
	 */
	public static void startTimerConnectSvr() {
		if (!MyStatus.center) {
			connTimer = new Timer();

			try {
				if(timerConnecter != null){
					timerConnecter.cancel();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

			timerConnecter = new TimerConnecter();
			connTimer.schedule(timerConnecter, 5000, 10000);
		}else{
			if(connTimer!=null){
				connTimer.cancel();
			}
		}
	}

	/**
	 * 启动鉴权
	 */
	//	public static void startTimerAuthSvr(){
	//		authTimer = new Timer();
	//		timerAuth = new TimerAuth();
	//		authTimer.schedule(timerAuth, 0, 20000);
	//	}

	/**
	 * 心跳包发送
	 */
	public synchronized static void startHeartBeat() {


		//启用心跳之前先判断是否有心跳正在运行
		if(heartTask != null){
			heartTask.cancel();
		}
		if(heartTimer != null){
			heartTimer.cancel();
		}

		heartTimer = new Timer();
		heartTask = new TimerHeartBeat();

		/*int htimer = 30;
			try {
				htimer = SPutil.defaultPref().getInt(PrefConstants.PARAMS_HEART_TIME, 30);
			} catch (Exception e) {
				AppLog.e(ExceptionUtil.getInfo(e));
				e.printStackTrace();
			}*/
		heartTimer.schedule(heartTask,5000, 1000);
		Log.e("启动心跳线程", "启动心跳线程");
	}

	/**
	 * 开始定时监控timer
	 * @param interval 间隔
	 * @param timer 次数
	 */
	//	public static void startTimingTrack(int interval,int num){
	//		try {
	//
	//			//启动之前先关闭
	//			if(timingTrack != null){
	//				timingTrack.cancel();
	//			}
	//			timingTrackTimer = new Timer();
	//			timingTrack = new TimingTrack(num);
	//			heartTimer.schedule(timingTrack, 0, interval*1000);
	//			/**
	//			 * 监听线程结束，回复原来的位置汇报
	//			 * 监听线程结束，回复原来的位置汇报----------------------------------------------
	//			 * 监听线程结束，回复原来的位置汇报
	//			 * 监听线程结束，回复原来的位置汇报
	//			 *
	//			 *
	//			 * 平台停止监控，取消此线程----------------------------------------------------------
	//			 */
	//		} catch (Exception e) {
	//			AppLog.e(ExceptionUtil.getInfo(e));
	//			e.printStackTrace();
	//		}
	//	}

	/**
	 * 停止定时监控
	 */
	//	public static void stopTimingTrack(){
	//		if(timingTrack != null){
	//			timingTrack.cancel();
	//		}
	//	}

	/**
	 * 开始定时监控timer
	 * @param fences 围栏列表
	 */
	public static void startTimerFence(List<AreaFence> fences){
		//		try {
		//
		//			//启动之前先关闭
		//			stopTimerFence();
		//
		//			fenceTimer = new Timer();
		//			fenceTask = new TimerFence(fences);
		//			fenceTimer.schedule(fenceTask, 1000, 1000);
		//		} catch (Exception e) {
		//			AppLog.e(ExceptionUtil.getInfo(e));
		//			e.printStackTrace();
		//		}
	}

	/**
	 * 停止定时监控
	 */
	public static void stopTimerFence(){
		//		if(fenceTimer != null){
		//			fenceTimer.cancel();
		//		}
		//		if(fenceTask != null){
		//			fenceTask.cancel();
		//		}
	}

	/**
	 * 关闭连接
	 */
	public static void stopComm(int type){

		try {
			try {
				if(channel != null){
					channel.close();
					channel = null;
				}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}

			if(type == 1){
//							Constants.authReason = 3;
				AppLog.savelog("【通讯平台】网络断开导致链接关闭......");
			}else if(type == 2){
//							Constants.authReason = 4;
				AppLog.savelog("【通讯平台】通讯平台连接异常导致链接关闭......");
			}else if(type == 3){
//							Constants.authReason = 4;
				AppLog.savelog("【通讯平台】通讯平台主动断开导致链接关闭......");
			}else if(type == 4){
//							Constants.authReason = 3;
				AppLog.savelog("【通讯平台】主动断开连接，检测到链接关闭超过3分钟......");
			}else if(type == 5){
//							Constants.authReason = 4;
				AppLog.savelog("【通讯平台】远程升级服务器IP或端口......");
			}else if(type == 6){
//							Constants.authReason = 4;
				AppLog.savelog("【通讯平台】通过行业通道界面主动操作服务器......");
			}else if(type == 0){
//							Constants.authReason = 1;
				AppLog.savelog("【通讯平台】开机启动连接平台......");
			}

			//关闭心跳定时器，重新连接
			//			if(heartTask != null){
			//				AppLog.i("关闭心跳定时器......");
			//				heartTask.cancel();
			//			}

			//if(isConnTimer){

			//			if(timerAuth != null){
			//				AppLog.i("【通讯平台】关闭鉴权定时器......");
			//				timerAuth.cancel();
			//			}

			times = 0;
			if(timerConnecter != null){
				AppLog.i("【通讯平台】关闭连接定时器......");
				timerConnecter.cancel();
			}
			channelFuture = null;
			isConnTimer = false;
			MyStatus.center = false;
			AppLog.savelog("监测多次连平台问题--stopComm");
			startTimerConnectSvr();
			//}
		} catch (Exception e) {
			AppLog.e(ExceptionUtil.getInfo(e));
			e.printStackTrace();
		}

	}

	public static void witeMsg(byte[] bodyByte){
		witeMsg(bodyByte, 0);
	}

	/**
	 * 发送消息
	 * @param bodyByte 数据包
	 * @param type 已失效，默认写0
	 */
	public static void witeMsg(byte[] bodyByte,int type){
		try {
			/*boolean flag = false;

			if(type==0){
				flag = true;
			}else{
				//电召参数设计 调度中心为开着才转发给奇华 0 关 1 开
				if(SPutil.getDianZhaoSetting().getInt("hytdswitch", 0)==1){
					flag = true;
				}
			}

			if(flag){*/
			if(channelFuture==null || channel == null){
				DispatchCenterClient.connect(1);
				AppLog.savelog("监测多次连平台问题：1");
			}
			//			Channel channel = channelFuture.getChannel();
			if(!channel.isConnected()){
				DispatchCenterClient.connect(1);
				AppLog.savelog("监测多次连平台问题：2");
			}
			if(!channelFuture.isSuccess()){
				DispatchCenterClient.connect(1);
				AppLog.savelog("监测多次连平台问题：3");
			}
			if(!MyStatus.center){
				DispatchCenterClient.connect(1);
				AppLog.savelog("监测多次连平台问题：4");
			}

			// 获得此对象的长度
			ChannelBuffer channelBuffer = ChannelBuffers.buffer(bodyByte.length);
			// 将 获得到的数组写入 channelBuffer中
			channelBuffer.writeBytes(bodyByte);
			// 发送到服务器端
			ChannelFuture lastWriteFuture = channel.write(channelBuffer);

			if (lastWriteFuture != null) {
				// 等待或监听数据
				lastWriteFuture.awaitUninterruptibly();
			}
			AppLog.i("【发送】"+Tools.parseByte2HexStr(bodyByte));
			AppLog.savelog("【终端发送数据】" +Tools.parseByte2HexStr(bodyByte));
			//			}
		} catch (Exception e) {
			AppLog.e(ExceptionUtil.getInfo(e));
			e.printStackTrace();
		}
	}

	public static boolean isConnect(){
		if(channelFuture==null || channel == null){
			return false;
		}
		//			Channel channel = channelFuture.getChannel();
		if(!channel.isConnected()){
			return false;
		}
		if(!channelFuture.isSuccess()){
			return false;
		}
		return true;
	}

	/**
	 * 发送消息
	 * @param bodyByte 数据包
	 */
	public static void witeMsgConnected(byte[] bodyByte){
		if(!MyStatus.center){
			DispatchCenterClient.connect(1);
		}
		if(channelFuture==null || channel == null){
			return;
		}
		//			Channel channel = channelFuture.getChannel();
		if(!channel.isConnected()){
			return;
		}
		if(!channelFuture.isSuccess()){
			return;
		}
		witeMsg(bodyByte);
	}
}
